/*
 * @Author: tomystery
 * @Date:   2017-09-11 17:55:41
 * @Last Modified by:   tomystery
 * @Last Modified time: 2017-09-14 11:20:05
 */
'use strict';

require('./index.css');
require('page/common/nav/index.js');
require('page/common/header/index.js');
var _mm = require('util/mm.js');
var _product = require('service/product-service.js');
var _cart = require('service/cart-service.js');
var templateIndex = require('./index.string');

var page = {
    data: {
        productId: _mm.getUrlParam('productId') || '',
    },
    init: function() {
        this.onLoad();
        this.bindEvent();


    },
    onLoad: function() {
        //没有传productId，自动跳回首页
        if (!this.data.productId) {
            _mm.goHome();
        }
        this.loadDetail();

    },
    bindEvent: function() {
        var _this = this;
        //图片预览
        $(document).on('mouseenter', '.p-img-item', function() {
            var imageUrl = $(this).find('.p-img').attr('src');
            console.log(imageUrl);
            $('.main-img').attr('src', imageUrl);
        });

        //count的操作
        //点+按钮范围在1-库存量之间，-按钮是不小于0
        $(document).on('click', '.p-count-btn', function() {
            var type = $(this).hasClass('plus') ? 'plus' : 'minus',
                $pCount = $('.p-count'),
                currentCount = parseInt($('.p-count').val()),
                minCount = 1,
                maxCount = _this.data.detailInfo.stock || 1;
            if (type === 'plus') {
                $pCount.val(currentCount < maxCount ? currentCount + 1 : maxCount);
            } else if (type === 'minus') {
                $pCount.val(currentCount > 1 ? currentCount - 1 : minCount);
            }
        });

        //加入购物车
        $(document).on('click', '.cart-add', function() {
            _cart.addToCart({
                productId: _this.data.productId,
                count: $('.p-count').val()
            }, function(res) {
                window.location.href = './result.html?type=cart-add';

            }, function(errMsg) {
                _mm.errorTips(errMsg);
            })

        });

    },
    loadDetail: function() {
        var _this = this;
        var html = '';
        var $pageContainer = $('.page-container');

        //loading
        $pageContainer.html('<div class="loading"></div>');
        //请求detail的信息
        _product.getDetailProduct(this.data.productId, function(res) {

            _this.filter(res);
            _this.data.detailInfo = res; //缓存detail的数据


            html = _mm.renderHtml(templateIndex, res);
            $pageContainer.html(html);

        }, function(errMsg) {

            $pageContainer.html('<p class="error-tip">此商品找不到了</p>');

        });
    },
    //filter数据匹配
    filter: function(data) {
        data.subImages = data.subImages.split(',');

    }


};
page.init();